<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8" />
    <title>🛒 商品购买系统（支持两种 createTime 格式，动态倒计时）</title>
    <style>
        /* ===== 基础样式 ===== */
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            margin: 0;
            padding: 20px;
            background: #f5f7fa;
            color: #333;
        }

        .container {
            max-width: 1000px;
            margin: 0 auto;
        }

        h1 {
            text-align: center;
            margin-bottom: 30px;
            color: #2c3e50;
        }

        /* ===== 未支付订单样式 ===== */
        .unpaid-order {
            border: 1px solid #ffcccc;
            border-radius: 8px;
            padding: 16px;
            margin-bottom: 16px;
            background: #fff5f5;
        }

        .unpaid-order h3 {
            margin: 0 0 10px 0;
            color: #d63384;
        }

        .unpaid-order p {
            margin: 5px 0;
            font-size: 14px;
        }

        .order-actions {
            margin-top: 10px;
        }

        .order-actions button {
            margin-right: 10px;
            padding: 6px 12px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }

        .btn-pay {
            background: #28a745;
            color: white;
        }
        .btn-pay:hover {
            background: #218838;
        }
        .btn-pay:disabled {
            background: #9ca3af;
            cursor: not-allowed;
        }

        .btn-cancel {
            background: #dc3545;
            color: white;
        }
        .btn-cancel:hover {
            background: #bb2d3b;
        }

        .countdown {
            font-weight: bold;
            color: #d63384;
        }

        /* ===== 商品列表样式 ===== */
        .product-list {
            display: flex;
            flex-wrap: wrap;
            gap: 16px;
        }

        .product-card {
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 16px;
            width: calc(25% - 16px);
            background: white;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        .product-card h3 {
            margin: 0 0 8px 0;
            font-size: 16px;
        }

        .product-card p {
            margin: 4px 0;
            font-size: 14px;
            color: #666;
        }

        .product-card button {
            margin-top: 8px;
            padding: 6px 12px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }

        .btn-buy {
            background: #28a745;
            color: white;
        }
        .btn-buy:hover {
            background: #218838;
        }

        .btn-detail {
            background: #007bff;
            color: white;
        }
        .btn-detail:hover {
            background: #0056b3;
        }

        /* ===== 支付页面（简化，弹出式） ===== */
        .order-payment {
            display: none;
            border: 1px solid #ccc;
            border-radius: 8px;
            padding: 20px;
            background: white;
            margin-top: 20px;
        }

        .order-payment.active {
            display: block;
        }

        input {
            padding: 6px;
            margin: 8px 0;
            width: 80px;
            border: 1px solid #ccc;
            border-radius: 4px;
        }

        .countdown-timer {
            font-weight: bold;
            color: #d63384;
        }
    </style>
</head>
<body>
<div class="container">
    <h1>🛍️ 商品购买系统</h1>

    <!-- 未支付订单区域 -->
    <div id="unpaidOrders">
        <!-- 未支付订单将通过 JS 动态插入 -->
    </div>

    <!-- 商品列表区域 -->
    <div id="productList" style="display: none;">
        <h2>📦 商品列表</h2>
        <div id="productCards" class="product-list">
            <!-- 商品卡片由 JS 动态插入 -->
        </div>
    </div>
</div>

<!-- 单个订单支付页面（简化，每个订单可独立支付/取消） -->
<div id="orderPayment" class="order-payment">
    <h2>💳 订单支付</h2>
    <div id="paymentInfo">
        <!-- 动态填充订单信息 -->
    </div>
    <div>
        <button class="btn-pay" onclick="payOrder()">✅ 支付</button>
        <button class="btn-cancel" onclick="cancelOrder()">❌ 取消订单</button>
    </div>
</div>

<script>
    const API_BASE_URL = 'http://localhost:8989';
    let unpaidOrders = [];
    let countdowns = {};

    // 📍 您需要确保这边传的是正确的用户 ID，目前写死为 1（可动态获取）
    const CURRENT_USER_ID = 1001;

    window.onload = async () => {
        await checkUnpaidOrders(CURRENT_USER_ID);

        if (unpaidOrders.length > 0) {
            renderUnpaidOrders();
        } else {
            document.getElementById('productList').style.display = 'block';
            await fetchProducts();
        }
    };

    // 调用后端接口 GET /hasUnpaid/{id}
    async function checkUnpaidOrders(userId) {
        try {
            const res = await fetch(`${API_BASE_URL}/api/order/hasUnpaid/${userId}`);
            const json = await res.json();
            const code = json.code;
            const data = json.data;

            if (code === 200 && data && Array.isArray(data) && data.length > 0) {
                unpaidOrders = data;
            } else {
                unpaidOrders = [];
            }
        } catch (err) {
            console.error('查询未支付订单失败:', err);
            unpaidOrders = [];
        }
    }

    // 渲染未支付订单列表，支持两种 createTime 格式，动态倒计时
    function renderUnpaidOrders() {
        const container = document.getElementById('unpaidOrders');
        let html = '<h2>⚠️ 您有未支付的订单，请尽快处理</h2>';

        unpaidOrders.forEach((order, index) => {
            console.log('订单 createTime:', order.createdAt)
            const create_time = new Date(order.createdAt);
            if (isNaN(create_time.getTime())) {
                console.error('订单 createTime 解析失败:', order.createdAt);
                return; // 若时间解析失败，跳过该订单（或可展示错误）
            }

            const now = new Date();
            const diffMs = now - create_time;
            const totalAllowedMs = 60000; // 30分钟
            const remainingMs = totalAllowedMs - diffMs;

            if (remainingMs <= 0) {
                html += `
            <div class="unpaid-order">
              <h3>订单号: ${order.orderNo}</h3>
              <p><strong>商品ID:</strong> ${order.productId}</p>
              <p><strong>数量:</strong> ${order.quantity}</p>
              <p><strong>金额:</strong> ¥${order.totalAmount}</p>
              <p><strong>状态:</strong> 未支付（已超时）</p>
              <p class="countdown">⏰ 订单可能已自动取消</p>
              <div class="order-actions">
                <button class="btn-pay" onclick="payUnpaidOrder(${index})" disabled>✅ 支付（已超时）</button>
                <button class="btn-cancel" onclick="cancelUnpaidOrder(${index})">❌ 取消订单</button>
              </div>
            </div>
          `;
            } else {
                const remainingSec = Math.ceil(remainingMs / 1000);
                html += `
            <div class="unpaid-order">
              <h3>订单号: ${order.orderNo}</h3>
              <p><strong>商品ID:</strong> ${order.productId}</p>
              <p><strong>数量:</strong> ${order.quantity}</p>
              <p><strong>金额:</strong> ¥${order.totalAmount}</p>
              <p><strong>状态:</strong> 未支付</p>
              <p class="countdown">支付剩余时间: <span id="countdown-${index}">${formatTime(remainingSec)}</span></p>
              <div class="order-actions">
                <button class="btn-pay" onclick="payUnpaidOrder(${index})">✅ 支付</button>
                <button class="btn-cancel" onclick="cancelUnpaidOrder(${index})">❌ 取消订单</button>
              </div>
            </div>
          `;
                startCountdown(index, remainingSec);
            }
        });

        container.innerHTML = html;
    }

    function formatTime(totalSeconds) {
        const mins = Math.floor(totalSeconds / 60);
        const secs = totalSeconds % 60;
        return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
    }

    function startCountdown(index, remainingSec) {
        countdowns[index] = setInterval(() => {
            remainingSec--;
            if (remainingSec <= 0) {
                clearInterval(countdowns[index]);
                document.getElementById(`countdown-${index}`).textContent = '已超时';
                document.getElementById(`countdown-${index}`).style.color = 'red';
                alert('⏰ 订单支付已超时，可能已被自动取消');
                return;
            }
            document.getElementById(`countdown-${index}`).textContent = formatTime(remainingSec);
        }, 1000);
    }

    async function payUnpaidOrder(index) {
        const order = unpaidOrders[index];
        if (!order) return;

        try {
            const res = await fetch(`${API_BASE_URL}/api/order/pay/success?orderNo=${order.orderNo}`, {
                method: 'POST'
            });
            const result = await res.json();
            if (!res.ok) throw new Error(result.message || '支付失败');

            alert('✅ 支付成功！');
            if (countdowns[index]) {
                clearInterval(countdowns[index]);
                delete countdowns[index];
            }
            unpaidOrders.splice(index, 1);
            renderUnpaidOrders();
            if (unpaidOrders.length === 0) {
                document.getElementById('unpaidOrders').innerHTML = '';
                document.getElementById('productList').style.display = 'block';
                await fetchProducts();
            }
        } catch (err) {
            alert('❌ 支付失败: ' + err.message);
        }
    }

    async function cancelUnpaidOrder(index) {
        const order = unpaidOrders[index];
        if (!order) return;

        if (!confirm('确定要取消此订单吗？')) return;

        try {
            const res = await fetch(`${API_BASE_URL}/api/order/cancel`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: `orderNo=${order.orderNo}`
            });
            const result = await res.json();
            if (!res.ok) throw new Error(result.message || '取消失败');

            if (result.code === 200 || result.message?.includes('成功')) {
                alert('✅ 订单已取消');
                unpaidOrders.splice(index, 1);
                renderUnpaidOrders();
                if (unpaidOrders.length === 0) {
                    document.getElementById('unpaidOrders').innerHTML = '';
                    document.getElementById('productList').style.display = 'block';
                    await fetchProducts();
                }
            } else {
                alert('❌ 取消失败: ' + (result.message || '未知错误'));
            }
        } catch (err) {
            alert('❌ 取消请求失败: ' + err.message);
        }
    }

    async function fetchProducts() {
        try {
            const res = await fetch(`${API_BASE_URL}/api/products`);
            const products = await res.json();
            renderProducts(products);
        } catch (err) {
            alert('加载商品失败: ' + err.message);
        }
    }

    function renderProducts(products) {
        const container = document.getElementById('productCards');
        let html = '';
        products.forEach(p => {
            html += `
          <div class="product-card">
            <h3>${p.id} - ${p.name || '未命名'}</h3>
            <p>💰 价格: ¥${p.price || 0}</p>
            <p>📦 库存: ${p.stock || 0}</p>
            <p>${p.description || ''}</p>
            <button class="btn-detail" onclick="showDetail(${p.id})">查看详情</button>
            <button class="btn-buy" onclick="buyProduct(${p.id})">购买</button>
          </div>
        `;
        });
        container.innerHTML = html;
    }

    async function showDetail(id) {
        try {
            const res = await fetch(`${API_BASE_URL}/api/product/${id}`);
            const p = await res.json();
            alert(`商品详情：\nID: ${p.id}\n名称: ${p.name}\n价格: ¥${p.price}\n库存: ${p.stock}\n描述: ${p.description || '无'}`);
        } catch (err) {
            alert('加载详情失败: ' + err.message);
        }
    }

    async function buyProduct(id) {
        let qty = prompt('请输入购买数量：');
        if (!qty || isNaN(qty) || qty <= 0) {
            alert('请输入有效的数量');
            return;
        }
        qty = parseInt(qty);

        try {
            const res = await fetch(`${API_BASE_URL}/api/order/place`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ productId: id, count: qty })
            });
            const result = await res.json();
            if (!res.ok) throw new Error(result.message || '下单失败');

            alert('✅ 下单成功！您可以在未支付订单中查看并支付');
            location.reload(); // 简单刷新以显示新订单
        } catch (err) {
            alert('❌ 下单失败: ' + err.message);
        }
    }

    function payOrder() {
        alert('支付功能需根据具体订单实现，这里为简化占位');
    }

    function cancelOrder() {
        alert('取消订单功能需根据具体订单实现，这里为简化占位');
    }
</script>
</body>
</html>